package common_package

import (
	"bufio"
	"log"
	"net"
	"os"
	"strings"
)

func Client() {
	conn, err := net.Dial("tcp", "192.168.160.140:8888")
	if err != nil {
		log.Println("连接服务器失败")
		return
	}

	reader := bufio.NewReader(os.Stdin)

	for {
		log.Println("请输入发送的信息")
		line, err := reader.ReadString('\n')
		if err != nil {
			log.Println("readString err =", err)
		}

		test := strings.Trim(line, " \r\n")

		if test == "exit" {
			log.Println("客户端退出")
			break
		}

		n, err := conn.Write([]byte(line))
		if err != nil {
			log.Println("发送失败")
		}
		log.Printf("客户端发送了%d字节\n", n)
	}
}

func Server() {
	log.Println("服务器启动...")
	listner, err := net.Listen("tcp", "0.0.0.0:8888")

	if err != nil {
		log.Println("监听发生错误", err)
		return
	}

	defer listner.Close()

	for {
		log.Println("等待客户端连接")
		conn, err := listner.Accept()
		if err != nil {
			log.Println("连接发生错误", err)
			continue
		} else {
			log.Println("接收成功")
			log.Printf("conn = %v,客户端ip=%v\n", conn, conn.RemoteAddr().String())
		}

		go process(conn)

	}
}

func process(conn net.Conn) {
	defer conn.Close()

	for {
		buf := make([]byte, 1024)
		log.Printf("服务器在等待客户端%s发送消息\n", conn.RemoteAddr().String())
		n, err := conn.Read(buf)

		if err != nil {
			log.Println("客户端退出")
			return
		}
		log.Println(string(buf[:n-1]))
	}
}
